package com.scedu.aspect;

import com.lly835.bestpay.utils.StringUtil;
import com.scedu.constant.CookieConstant;
import com.scedu.exception.SellAuthorizeException;
import com.scedu.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;
    /*
    验证卖家用户登录
     */
    @Pointcut("execution(public * com.scedu.controller.Seller*.*(..))" +//切入点 com.scedu.controller包中以Seller为开始的控制器
               "&& !execution(public  * com.scedu.controller.SellerUserController.*(..))" //排除掉SellerUserController
    )
    public  void verify(){

    }
    @Before("verify()")
    public  void doVerfiy(){
        ServletRequestAttributes attributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpServletRequest=  attributes.getRequest();
        //查询cookie
        Cookie cookie= CookieUtil.get(httpServletRequest, CookieConstant.cookiename);
        if (cookie==null){
            log.warn("登录失败,cookie查不到");
            throw new SellAuthorizeException();

        }
        //去redis 里面查询
        String tokenValue=redisTemplate.opsForValue().get(cookie.getValue());
        if (StringUtil.isEmpty(tokenValue)){
            log.warn("登录失败,redis查不到");
            throw new SellAuthorizeException();
        }
    }
}
